package com.itheima.springbootwebtlias.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.springbootwebtlias.mapper.ClazzMapper;
import com.itheima.springbootwebtlias.pojo.ClaQueryParam;
import com.itheima.springbootwebtlias.pojo.Clazz;
import com.itheima.springbootwebtlias.pojo.PageResult;
import com.itheima.springbootwebtlias.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;


    @Override
    public List<Clazz> selectAll() {
        List<Clazz> clazzs = clazzMapper.selectAll();
        return clazzs;
    }

    @Override
    public void saveClazz(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        clazzMapper.saveClazz(clazz);
    }

    // 班级列表分页查询
    @Override
    public PageResult page(ClaQueryParam queryParam) {
        PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());

        Page<Clazz> page = (Page<Clazz>) clazzMapper.selectByCondition(queryParam);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());

        return pageResult;
    }

    // 根据id删除班级
    @Override
    public void removeById(Integer id) {
        //查询当前班级下是否存在学员
        //如果存在学员，则不允许删除
        Integer count = clazzMapper.selectByClazzId(id);
        if(count != 0){
            //存在学员，不允许删除
            throw new RuntimeException("当前班级存在学员，不允许删除");
        }

        // 调用持久层Mapper,删除指定班级
        clazzMapper.removeById(id);
    }

    // 根据id查询班级
    @Override
    public Clazz queryById(Integer id) {
        Clazz clazz = clazzMapper.queryById(id);
        return clazz;
    }

    // 修改班级信息
    @Override
    public void update(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.update(clazz);
    }
}
